package cn.qidisoft.edu.hzjt.controller.zyc;

import cn.qidisoft.core.common.context.ApplicationContextConfigUtil;
import cn.qidisoft.core.common.log.LoggerAdapter;
import cn.qidisoft.core.common.log.LoggerAdapterFactory;
import cn.qidisoft.core.common.pagination.Page;
import cn.qidisoft.core.common.pagination.PaginationBean;
import cn.qidisoft.core.util.file.FileUtil;
import cn.qidisoft.core.util.moffice.excel.ExpExcelUtil;
import cn.qidisoft.core.util.uuid.UUIDGenerator;
import cn.qidisoft.edu.hzjt.annotation.SysLogger;
import cn.qidisoft.edu.hzjt.constants.Constant;
import cn.qidisoft.edu.hzjt.controller.BaseController;
import cn.qidisoft.edu.hzjt.exception.RPCException;
import cn.qidisoft.edu.hzjt.model.BjxxClassMaterialFile;
import cn.qidisoft.edu.hzjt.model.ResponseResult;
import cn.qidisoft.edu.hzjt.model.UserEmployee;
import cn.qidisoft.edu.hzjt.model.zyc.ScientificResearch;
import cn.qidisoft.edu.hzjt.model.zyc.ScientificResearchAtt;
import cn.qidisoft.edu.hzjt.service.zyc.IScientificResearchAttService;
import cn.qidisoft.edu.hzjt.service.zyc.IScientificResearchService;
import cn.qidisoft.edu.hzjt.utils.CommonUtils;
import cn.qidisoft.edu.hzjt.utils.LogType;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.io.FilenameUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.*;

/***
 * 科研成果
 */
@Controller
@RequestMapping(value = "scientificResearch")
public class ScientificResearchController{

    protected static final LoggerAdapter LOGGER =
            LoggerAdapterFactory.getLogger(LogType.HZJT_LOGGER.val);

    @Autowired
    IScientificResearchService scientificResearchService;
    @Autowired
    IScientificResearchAttService scientificResearchAttService;

    private static String upload = null;

    static {
        upload = ApplicationContextConfigUtil.getString("file.path", null);
    }
    private static Map<String, List<ScientificResearchAtt>> picMap = new HashMap<>();

    @RequestMapping(value = "/index")
    public String index(ModelMap model, HttpServletRequest request) {
        return "zyc/scientificResearch/scientificResearchList";
    }

    @RequestMapping(value = "/list")
    @ResponseBody
    public ResponseResult list(
            ModelMap model, HttpServletRequest request,
            @RequestParam(value = "rows", required = false) String pageSize,
            @RequestParam(value = "page", required = false) String currentPage,
            ScientificResearch data) {
        try {
            data.setGid(UUIDGenerator.genReqID());
            Page page = new Page();
            page.setCurrPage(currentPage == null ? 0 : Integer.valueOf(currentPage));
            page.setPageSize(pageSize == null ? Constant.PageSize : Integer.valueOf(pageSize));
            BaseController.setSortByColumn(request, "createTime", "desc");
            data.setOrderField((String) request.getAttribute("orderField"));
            data.setOrderFlag((String) request.getAttribute("orderFlag"));
            Map<String, Object> queryMap = new HashMap<String, Object>();
    		String begintime = request.getParameter("begintime");
    		String endtime = request.getParameter("endtime");
    	    queryMap.put("ScientificResearch", data);
    		queryMap.put("begintime", begintime);
    		queryMap.put("endtime", endtime);
    		String cgjb = request.getParameter("cgjb");
    		String author = request.getParameter("author");
    		String cgmc = request.getParameter("cgmc");
    		String cglx = request.getParameter("cglx");
    		if(null != cgmc) {
    			cgmc = cgmc.trim();
    		}
    		if(null != author) {
    			author = author.trim();
    		}
    		if(null != cglx) {
    			cglx = cglx.trim();
    		}
    		queryMap.put("cglx", cglx);
    		queryMap.put("cgmc", cgmc);
    		queryMap.put("cgjb", cgjb);
    		queryMap.put("author",author);
            PaginationBean<ScientificResearch> paginationBean = scientificResearchService.queryPageList(queryMap, page);
            ResponseResult result = new ResponseResult();
            result.setTotal(paginationBean.getTotalRecords());
            result.setRows(paginationBean.getPageList());
            return result;
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
        }
        return null;
    }

    @RequestMapping(value = "/addInInt", method = RequestMethod.GET)
    public String add(ModelMap model, HttpServletRequest request) {
        UserEmployee userEmployee =
                (UserEmployee) request.getSession().getAttribute(Constant.LOGIN_CONSOLE_USER);
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String today = dateFormat.format(new Date());
        Map<String, Object> reMap = new HashMap<>();
        reMap.put("createTime", today);
        reMap.put("creatorName", userEmployee.getXm());
        request.setAttribute("entity", reMap);
        request.setAttribute("msg", BaseController.getParameter("msg"));
        BaseController.removeParameter("msg");
        return "zyc/scientificResearch/scientificResearchAdd";
    }

    @SysLogger(description = "社团活动管理信息", moduleName = "社团活动管理", method = "新增保存")
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public String save(ModelMap model, HttpServletRequest request,
                       ScientificResearch data) {
        try {
            UserEmployee userEmployee =
                    (UserEmployee) request.getSession().getAttribute(Constant.LOGIN_CONSOLE_USER);
            String action = request.getParameter("action")==null?"":request.getParameter("action");
            //data.setXkid(userEmployee.getEmid());
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
         			String formatStr =formatter.format(new Date());
            data.setGid(UUIDGenerator.genReqID());
            data.setCreatorId(userEmployee.getUid());
            data.setCreatorName(userEmployee.getXm());
            data.setCreateTime(formatStr);
            scientificResearchService.insert(data);

            String path = upload;
            List<ScientificResearchAtt> docFileResourceList = picMap
                    .get(String.valueOf(userEmployee.getUserid()));
            if (docFileResourceList != null && !docFileResourceList.isEmpty()) {
                MultipartFile file = null;
                String filePath =CommonUtils.createSaveFilePath("JKY_JKS_KYCG", userEmployee.getUserid() );
                int orders = 0;
                for (ScientificResearchAtt r : docFileResourceList) {
                    file = r.getMufile();
                    r.setParentId(data.getKyid());
                    String name = file.getOriginalFilename();// 获取上传文件名
                    InputStream in = r.getInputStream();// 获取文件对象
                    int pos = name.lastIndexOf(".");
                    String lastname = name.substring(pos, name.length());
                    // 文件保存的路径
                    String savePath = path + CommonUtils.fileSeprator + filePath;
                    FileUtil.saveFile(savePath, in, r.getGid() + lastname);
                    r.setGid(r.getGid());// 附件id
                    r.setFileName(name);
                    r.setOrders(orders);
                }
                scientificResearchAttService.batchInserts(docFileResourceList);
                //保存成功后，清除明细
                picMap.remove(String.valueOf(userEmployee.getUserid()));
            }
            BaseController.setParameter("msg", "添加成功");
            if (action.equals("add")) {
                return "redirect:addInInt";
            }else{
                return "redirect:./view?kyid=" + data.getKyid();
            }
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("添加信息 add [{}] error," + this.getClass().getName() + "=[{}]",
                    this.getClass().getName(), e.getMessage());
            return "error/error";
        }
    }
    /**
   	 * 进入预览页面
   	 * @param model
   	 * @param request
   	 * @return
   	 */
   	@RequestMapping(value = "/view")
   	public String view(HttpServletRequest request) {
   		try {
   			String  kyid = request.getParameter("kyid");
   			ScientificResearch sResearch = new ScientificResearch();
   			sResearch.setKyid(Integer.parseInt(kyid));
   			ScientificResearch scientificResearch = scientificResearchService.getPlanning(sResearch);
   			if(null != scientificResearch.getFbrq()) {
   				scientificResearch.setFbrq(scientificResearch.getFbrq().substring(0, scientificResearch.getFbrq().length()-2));   				
   			}
   			if(null != scientificResearch.getCreateTime()) {
   				scientificResearch.setCreateTime(scientificResearch.getCreateTime().substring(0, scientificResearch.getCreateTime().length()-2));   				
   			}
   			// 查询附件信息
   			List<ScientificResearchAtt> dataList = scientificResearchAttService.getPlanningAtt(sResearch);
   			request.setAttribute("data", scientificResearch);
   			request.setAttribute("dataList", dataList);
   			return "zyc/scientificResearch/view";
   		} catch (Exception e) {
   			LOGGER.error("获得xxxxx信息 addStudentDemoForward [{}] error," + this.getClass().getName() + "=[{}]",
   					this.getClass().getName(), e.getMessage());
   			return "error/error";
   		}
   	}
	@RequestMapping("/edit")
	public String edit(ModelMap model, HttpServletRequest request) {
		try {
			String  kyid = request.getParameter("kyid");
   			ScientificResearch sResearch = new ScientificResearch();
   			sResearch.setKyid(Integer.parseInt(kyid));
   			ScientificResearch scientificResearch = scientificResearchService.getPlanning(sResearch);
   			if(null != scientificResearch.getFbrq()) {
   				scientificResearch.setFbrq(scientificResearch.getFbrq().substring(0, scientificResearch.getFbrq().length()-2));   				
   			}
   			if(null != scientificResearch.getCreateTime()) {
   				scientificResearch.setCreateTime(scientificResearch.getCreateTime().substring(0, scientificResearch.getCreateTime().length()-2));   				
   			}
   			// 查询附件信息
   			List<ScientificResearchAtt> dataList = scientificResearchAttService.getPlanningAtt(sResearch);
   			request.setAttribute("data", scientificResearch);
   			request.setAttribute("dataList", dataList);
			return "zyc/scientificResearch/edit";
		} catch (Exception e) {
			LOGGER.error("获得xxxxx信息 addStudentDemoForward [{}] error," + this.getClass().getName() + "=[{}]",
					this.getClass().getName(), e.getMessage());
			return "error/error";
		}
	}
	 @SysLogger(description = "社团活动管理信息", moduleName = "社团活动管理", method = "新增保存")
	    @RequestMapping(value = "/update", method = RequestMethod.POST)
	    public String update(ModelMap model, HttpServletRequest request,
	                       ScientificResearch data) {
	        try {
	            UserEmployee userEmployee =
	                    (UserEmployee) request.getSession().getAttribute(Constant.LOGIN_CONSOLE_USER);
	            String action = request.getParameter("action")==null?"":request.getParameter("action");
	            //data.setXkid(userEmployee.getEmid());
	            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	         			String formatStr =formatter.format(new Date());
	            data.setGid(UUIDGenerator.genReqID());
	            data.setCreatorId(userEmployee.getUid());
	            data.setCreatorName(userEmployee.getXm());
	            data.setCreateTime(formatStr);
	            scientificResearchService.update(data);
	            
	            String path = upload;
	            List<ScientificResearchAtt> docFileResourceList = picMap
	                    .get(String.valueOf(userEmployee.getUserid()));
	            if (docFileResourceList != null && !docFileResourceList.isEmpty()) {
	                MultipartFile file = null;
	                String filePath =CommonUtils.createSaveFilePath("JKY_JKS_KYCG", userEmployee.getUserid() );
	                int order = 0;
	                for (ScientificResearchAtt r : docFileResourceList) {
	                    file = r.getMufile();
	                    r.setParentId(data.getKyid());
	                    String name = file.getOriginalFilename();// 获取上传文件名
	                    InputStream in = r.getInputStream();// 获取文件对象
	                    int pos = name.lastIndexOf(".");
	                    String lastname = name.substring(pos, name.length());
	                    // 文件保存的路径
	                    String savePath = path + CommonUtils.fileSeprator + filePath;
	                    FileUtil.saveFile(savePath, in, r.getGid() + lastname);
	                    r.setGid(r.getGid());// 附件id
	                    r.setFileName(name);
	                    r.setOrders(order);
	                }
	                scientificResearchAttService.batchInserts(docFileResourceList);
	                //保存成功后，清除明细
	                picMap.remove(String.valueOf(userEmployee.getUserid()));
	            }
	            BaseController.setParameter("msg", "添加成功");
	            if (action.equals("add")) {
	                return "redirect:addInInt";
	            }else{
	                return "redirect:./view?kyid=" + data.getKyid();
	            }
	        } catch (Exception e) {
	            e.printStackTrace();
	            LOGGER.error("添加信息 add [{}] error," + this.getClass().getName() + "=[{}]",
	                    this.getClass().getName(), e.getMessage());
	            return "error/error";
	        }
	    }
	
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    public String delete(ModelMap model, HttpServletRequest request) {
        try {
            String[] idList = request.getParameter("idList").split(",");
            ScientificResearch data = new ScientificResearch();
            data.setIds(idList);
            scientificResearchService.delete(data);
            BaseController.setParameter("msg", "删除成功");
            return "redirect:index";
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("删除 delete [{}] error," + this.getClass().getName() + "=[{}]",
                    this.getClass().getName(), e.getMessage());
            return "error/error";
        }
    }

    /**   
     * 新增删除
     *
     * @param file
     * @param request
     * @param response
     */
    @RequestMapping(value = "/source_upload", method = RequestMethod.POST)
    public @ResponseBody void loadFile(@RequestParam("file") MultipartFile file,
                                       HttpServletRequest request, HttpServletResponse response) {
        List<ScientificResearchAtt> list = new ArrayList<>();
        UserEmployee userEmployee = (UserEmployee) request.getSession()
                .getAttribute(Constant.LOGIN_CONSOLE_USER);
        List<ScientificResearchAtt> docFileResourceList = picMap
                .get(String.valueOf(userEmployee.getUserid()));
        // 本地env配置路径
        String path = upload;
        try {
            String gid = UUID.randomUUID().toString();
            String name = file.getOriginalFilename();// 获取上传文件名
            // 获取文件后缀名称
            String extend = FilenameUtils.getExtension(name);
            ScientificResearchAtt docFile = new ScientificResearchAtt();
            String filePath =CommonUtils.createSaveFilePath("JKY_JKS_KYCG", userEmployee.getUserid() );
            if (!file.isEmpty()) {
                // 文件的大小
                docFile.setFileSize(String.valueOf(FileUtil.FormetFileSize(Long.valueOf(file.getSize()))));
                docFile.setFileName(name);
                docFile.setGid(gid);
                docFile.setExtension(FileUtil.getFileExtendName(name).toLowerCase());
                docFile.setMufile(file);
                docFile.setInputStream(file.getInputStream());
                /**
                 * 2018.12.12
                 * 当前业务目录/用户ID/上传当前时间（到天）/随机生成uuid文件名称
                 */
                docFile.setFilePath(filePath + gid + "." + extend);
                docFile.setSysfilepath(path + CommonUtils.fileSeprator + filePath + gid + "." + extend);
                docFile.setOrders(0);
                
                if (docFileResourceList != null && docFileResourceList.size() > 0) {
                    docFileResourceList.add(docFile);
                    picMap.put(String.valueOf(userEmployee.getUserid()), docFileResourceList);
                } else {
                    list.add(docFile);
                    picMap.put(String.valueOf(userEmployee.getUserid()), list);
                }
                LOGGER.info("附件上传成功！");
            }
            PrintWriter writer = null;
            BjxxClassMaterialFile docFile2 = new BjxxClassMaterialFile();
            docFile2.setFilepath(docFile.getFilePath());
            // 文件名称
            docFile2.setFilename(docFile.getFileName());
            docFile2.setSysfilepath(path + CommonUtils.fileSeprator + filePath  + gid + "." + extend);
            writer = response.getWriter();
            String json = JSONObject.toJSONString(docFile2);
            writer.write(json);
            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /**
  	 * 
  	 * @Title: source_upload_update @Description: 删除附件 @param @param
  	 *         fileId @param @param request @param @param response @param @return
  	 *         参数 @return Map<String,Object> 返回类型 @throws
  	 */
  	@RequestMapping(value = "/source_upload_update", method = RequestMethod.POST)
  	public @ResponseBody Map<String, Object> source_upload_update(@RequestParam("fileId") String fileId,
  			@RequestParam("filePath") String filePath, HttpServletRequest request, HttpServletResponse response) {
  		Map<String, Object> dataMap = new HashMap<String, Object>();
  		try {
  			// 删除表记录
  			ScientificResearchAtt attEntity = new ScientificResearchAtt();
  			attEntity.setFileId(Integer.parseInt(fileId));
  			
  			ScientificResearchAtt newAttEntity = scientificResearchAttService.queryByFileId(attEntity);
  			filePath = newAttEntity.getFilePath();
  			scientificResearchAttService.deleteAccessory(attEntity);
  			
  			// 删除原始文件
  			File file = new File(upload + CommonUtils.fileSeprator + filePath);
  			file.delete();
  			
  			dataMap.put("success", "0000");
  		} catch (Exception e) {
  			LOGGER.error("调用services网络异常", e);
  			dataMap.put("success", "-9999");
  		}
  		return dataMap;
  	}
  	 /**
		 * 学校发展规划下载
		 * 
		 * @param form
		 * @param request
		 * @param response
		 * @return
		 * @throws Exception
		 */
		@RequestMapping(value = "/export_scientificResearch")
		public @ResponseBody void export_scientificResearch(HttpServletRequest request, HttpServletResponse response,ScientificResearch data) throws Exception {
			try {
				Map<String, Object> queryMap = new HashMap<String, Object>();
	    		String begintime = request.getParameter("begintime");
	    		String endtime = request.getParameter("endtime");
	    	    queryMap.put("ScientificResearch", data);
	    		queryMap.put("begintime", begintime);
	    		queryMap.put("endtime", endtime);
	    		String subject = request.getParameter("cgjb");
	    		String author = request.getParameter("author");
	    		String cgmc = request.getParameter("cgmc");
	    		String cglx = request.getParameter("cglx");
	    		if(null != cgmc) {
	    			cgmc = cgmc.trim();
	    		}
	    		if(null != author) {
	    			author = author.trim();
	    		}
	    		if(null != cglx) {
	    			cglx = cglx.trim();
	    		}
	    		queryMap.put("cglx", cglx);
	    		queryMap.put("cgmc", cgmc);
	    		queryMap.put("subject", subject);
		    	queryMap.put("author",author);
				List<ScientificResearch> datalist = scientificResearchService.getPlanningList(queryMap);
				String[][] title_name = { { "id", "成果名称", "成果类型", "成果级别", "鉴定单位","作者","发布刊物名称","发表时间", "创建日期"} };
				String[] title_style = { "hwzs_16_bold_25","hwzs_16_bold_25","hwzs_16_bold_25","hwzs_16_bold_25", "hwzs_16_bold_25",
						"hwzs_16_bold_25" ,"hwzs_16_bold_25" ,"hwzs_16_bold_25" ,"hwzs_16_bold_25" };
				String fileName = "科研成果";
				String[] remark = { "" };
				List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
				if (datalist != null && !datalist.isEmpty()) {
					for (ScientificResearch res : datalist) {
						Map<String, Object> map = new LinkedHashMap<String, Object>();
						map.put("kyid", res.getKyid());
						map.put("cgmc", res.getCgmc());
						map.put("cglx", res.getCglx());
						map.put("cgjb", res.getCgjb());
						map.put("jddw", res.getJddw());
						map.put("author", res.getAuthor());
						map.put("fbkwmc", res.getFbkwmc());
						map.put("fbrq", res.getFbrq());
						map.put("createtime", res.getCreateTime());
						list.add(map);
					}
				}
				HSSFWorkbook wb = ExpExcelUtil.getWorkBookExcel(title_name, title_style, 100, remark, fileName, list);
				try {
					String filenameConvert = "科研成果";/* new String(fileName.getBytes("GB2312"), "ISO8859-1"); */
					response.reset();
					response.setContentType("application/vnd.ms-excel;charset=utf-8");
					response.setHeader("Content-Disposition",
							"attachment;filename=" + new String((filenameConvert + ".xls").getBytes(), "iso-8859-1"));
					response.setDateHeader("Expires", 0);
					ServletOutputStream os = response.getOutputStream();
					wb.write(os);
					os.flush();
				} catch (Exception e) {
					System.out.println("网络连接断开，可能用户取消了导出");
				}
			} catch (RPCException e) {
				LOGGER.error("获得xxxxx信息 exportStudentjobList [{}] error," + this.getClass().getName() + "=[{}]",
						this.getClass().getName(), e.getMessage());
			}
		}
    /**
     * 新增删除服务器的文件
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/deletefile", method = RequestMethod.POST)
    public @ResponseBody Map<String, Object> deleteFile(HttpServletRequest request) {

        Map<String, Object> dataMap = new HashMap<String, Object>();
        try {
            UserEmployee userEmployee = (UserEmployee) request.getSession()
                    .getAttribute(Constant.LOGIN_CONSOLE_USER);
            // env配置路径
            String path = upload;
            String filepath = request.getParameter("filepath");
            LOGGER.info("文件的原始路径===" + filepath);
            // 文件的全路径
            String fullpath = null;
            // 文件名称
            String filename = null;
            // 文件名无后缀
            String fileNoSuffix = null;
            if (filepath.indexOf("prefix") == -1) {
                // 文件的文件名称
                fileNoSuffix = filepath.split(",")[0];
                String sec = filepath.split(",")[1];
                // 文件的后缀
                String suffix = sec.substring(sec.indexOf("."));
                // 文件名无后缀加上后缀
                filename = fileNoSuffix + suffix;
                // 文件的全路径
                fullpath = path + CommonUtils.fileSeprator + fileNoSuffix;
                // FileUtil.deleteFile(fullpath, filename);//删除文件目录下面的文件
                // FileUtils.forceDelete(new File(fullpath)); //删除文件目录
            } else {
                return dataMap;
            }
            List<ScientificResearchAtt> noticeNewsFilepathList = picMap
                    .get(String.valueOf(userEmployee.getUserid()));
            // 删除list里面前台删除的前台信息图片附件表
            if (noticeNewsFilepathList != null && !noticeNewsFilepathList.isEmpty()) {
                for (ScientificResearchAtt obj : noticeNewsFilepathList) {
                    if (obj.getFileName().equals(fileNoSuffix)) {
                        noticeNewsFilepathList.remove(obj);
                        break;
                    }
                }
            }
            // 先删除
            picMap.remove(userEmployee.getUserid());
            // 后添加
            picMap.put(String.valueOf(userEmployee.getUserid()), noticeNewsFilepathList);
            dataMap.put("success", "0000");
            return dataMap;
        } catch (Exception e) {
            dataMap.put("success", "-9999");
            return dataMap;
        }
    }

}
